package com.example.controller;

import com.example.entity.Device;
import com.example.service.DeviceService;
import com.example.util.AjaxResult;
import com.example.util.PageResult;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/api")
public class DeviceController {

    @Autowired
    private DeviceService deviceService;

    /**
     * 添加新设备
     * @param device
     * @return
     */
    @PostMapping("/devices")
    public AjaxResult addDevice(@RequestBody Device device) {
        int dev = deviceService.addDevice(device);
        if (dev > 0){
            return AjaxResult.success("添加成功", dev);
        }else {
            return AjaxResult.error("添加失败");
        }
    }

    /**
     * 获取设备列表(可分页)
     * @param type
     * @param status
     * @return
     */
    @GetMapping("/devices")
    public AjaxResult getDeviceList(@RequestParam(required = false) Integer type,
                                    @RequestParam(required = false) Integer status){
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("type", type);
        hashMap.put("status", status);
        PageResult<Device> devicePageResult = deviceService.pageDevices(hashMap);
        if (ObjectUtils.isNotEmpty(devicePageResult)){
            return AjaxResult.success("查询成功", devicePageResult);
        }else {
            return AjaxResult.error("查询失败");
        }
    }

    /**
     * 根据id修改设备状态
     * @param deviceId
     * @return
     */
    @PutMapping("/devices/{deviceId}/status")
    public AjaxResult updateDevice(@PathVariable Integer deviceId,@RequestParam Integer status){
        Integer count = deviceService.updateDeviceById(deviceId,status);
        if (count > 0){
            return AjaxResult.success("更新成功", count);
        }else {
            return AjaxResult.error("更新失败");
        }
    }



}
